package com.github.cyf.rateLimit.annotation;

import com.github.cyf.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenyifan
 * @create 2025-02-05 10:44
 */
@Aspect
@Component
@Slf4j
public class LeakyBucketRateLimitAspect {

    private final ConcurrentHashMap<String, LeakyBucketLimiter> limiters = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.github.cyf.rateLimit.annotation.LeakyBucketRateLimit)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        LeakyBucketRateLimit leakyBucketRateLimit = method.getAnnotation(LeakyBucketRateLimit.class);
        int capacity = leakyBucketRateLimit.capacity();
        int leakRate = leakyBucketRateLimit.leakRate();

        LeakyBucketLimiter limiter = limiters.computeIfAbsent(method.toString(), k -> LeakyBucketLimiter.create(capacity, leakRate));

        if (limiter.tryAcquire()) {
            return joinPoint.proceed();
        } else {
            throw new BizException("请求过于频繁，请稍后重试");
        }
    }
}
